<script setup name="ToolGenTemplateIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import { parseTime } from "@/utils/aidex";
import { listTable, importTable, delTable, genCode } from "@/api/tool/gen";
import TableList from "./modules/table/index.vue";
import { downLoadZip } from "@/utils/zipdownload";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  showdbTable: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  // 搜索
  search: {
    name: "",
    deptId: ""
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: []
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});

// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.tableName &&
    (params.tableName = data.value.search.tableName);
  listTable(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.rows;
    pagination.value.total = res.total;
  });
}

// 编辑
function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.tableId
      }
    });
  } else {
    data.value.formModeProps.id = row.tableId;
    data.value.formModeProps.visible = true;
  }
}
// 添加
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  console.log("row", row);
  const ids =
    row.tableId ||
    data.value.batch.selectionDataList.map((item) => {
      return item.tableId;
    });
  const names =
    row.tableName ||
    data.value.batch.selectionDataList.map((item) => {
      return item.tableName;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delTable(ids).then((res) => {
          if (res.code == 200) {
            ElMessage.success({
              message: "删除成功",
              center: true
            });
            getDataList();
          }
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
// 导入
function importTables() {
  data.value.showdbTable = true;
}
const tablelistRef = ref(null);
// 选择 表格 确认
function checkIsTable() {
  tablelistRef.value.checkTable();
}
// 子穿值给父
function checkTable(item) {
  data.value.showdbTable = item.unshow;
  data.value.loading = true;
  if (item.checkTable.length > 0) {
    let tables = item.checkTable.map((res) => {
      return res.tableName;
    });
    importTable({ tables: tables.join(",") }).then((res) => {
      if (res.code == 200) {
        getDataList();
      }
    });
  }
}

function zipupload(row) {
  data.value.loading = true;
  const tableNames = row.tableName || this.tableNames;
  if (tableNames === "" || tableNames.length === 0) {
    ElMessage.error({
      message: "请选择要生成的数据",
      center: true
    });
    data.value.loading = false;
    return;
  }
  if (row.genType !== undefined) {
    if (row.genType === "1") {
      genCode(row.tableName)
        .then((response) => {
          ElNotification({
            type: "success",
            title: "温馨提示",
            dangerouslyUseHTMLString: true,
            message: response.msg,
            position: "top-right",
            duration: 5000
          });
        })
        .finally(() => {
          data.value.loading = false;
        });
    } else {
      downLoadZip("tool/gen/batchGenCode?tables=" + tableNames, "aidex");
      data.value.loading = false;
    }
  } else {
    data.value.selectionDataList.forEach((node) => {
      if (node.genType === "1") {
        genCode(node.tableName)
          .then((response) => {
            ElNotification({
              type: "info",
              title: "温馨提示",
              dangerouslyUseHTMLString: true,
              message: response.msg,
              position: "top-right",
              duration: 5000
            });
          })
          .finally(() => {
            data.value.loading = false;
          });
      } else {
        downLoadZip("tool/gen/batchGenCode?tables=" + node.tableName, "ruoyi");
        data.value.loading = false;
      }
    });
  }
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="5">
              <el-form-item label="表名称">
                <el-input
                  v-model="data.search.tableName"
                  placeholder="请输入表名称"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="作者">
                <el-input
                  v-model="data.search.functionAuthor"
                  placeholder="请输入作者"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item>
                <el-button type="primary" @click="currentChange()">
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:search" />
                    </el-icon>
                  </template>
                  查询
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button-group>
            <el-button type="primary" @click="importTables">
              <template #icon>
                <el-icon>
                  <svg-icon name="ant-design:cloud-upload-outlined" />
                </el-icon>
              </template>
              导入
            </el-button>
            <el-button type="danger" @click="onDel">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:close-bold" :size="20" />
                </el-icon>
              </template>
              删除
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
      <div style="height: calc(100vh - 380px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
        >
          >
          <el-table-column type="selection" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80"
          />
          <el-table-column
            prop="tableName"
            label="表名称"
            show-overflow-tooltip
          />
          <el-table-column prop="tableComment" label="表描述" align="center" />
          <el-table-column prop="className" label="实体" align="center" />
          <el-table-column
            prop="functionAuthor"
            label="作者"
            align="center"
            width="80"
          />
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column label="操作" width="260" align="center">
            <template #default="scope">
              <el-button-group>
                <!-- <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:eye-outlined" />
                    </el-icon>
                  </template>
                  预 览
                </el-button> -->
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="zipupload(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:cloud-download-outlined" />
                    </el-icon>
                  </template>
                  生成代码
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:edit-filled" />
                    </el-icon>
                  </template>
                  编 辑
                </el-button>

                <el-button
                  type="danger"
                  text
                  size="small"
                  @click="onDel(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:close-bold" />
                    </el-icon>
                  </template>
                  删除
                </el-button>
                <!-- <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:cloud-sync-outlined" />
                    </el-icon>
                  </template>
                  同 步
                </el-button>

                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:apartment-outlined" />
                    </el-icon>
                  </template>
                  创建菜单
                </el-button> -->
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
    <!--数据库导入-->
    <el-dialog
      v-model="data.showdbTable"
      title="数据库表选择"
      width="50%"
      draggable
      top="5vh"
    >
      <TableList ref="tablelistRef" @checkTable="checkTable"></TableList>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.showdbTable = false">取消</el-button>
          <el-button type="primary" @click="checkIsTable">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--编辑-->
    <!-- <el-dialog v-model="data.showdbTable" title="编辑" width="100%" fullscreen>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.showdbTable = false">取消</el-button>
          <el-button type="primary" @click="checkIsTable">确定</el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
